package cn.tedu.sp02.item.controller;


import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.web.util.JsonResult;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@RestController
public class ItemController {
    @Autowired
    private ItemService itemService;

    @Value("${server.port}")
    private int port;

    //获取订单商品列表
    /**
     * JsonResult - 响应结果的封装对象
     *              - code  相应的状态码 可以是http状态 或者也可以自己任意定义的
     *              - msg   提示消息
     *              - data  发回的相应数据对象
     */
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
        log.info("server.port="+port+", orderId="+orderId);

        List<Item> items = itemService.getItems(orderId);

        if (Math.random()<0.9){
            int i = new Random().nextInt(5000);
            System.out.println("延迟："+i);
            Thread.sleep(i);
        }

        return JsonResult.ok().data(items);
    }

    //减少商品库存
    /**
     *客户端发送的请求协议，商品集合要包含在请求协议体中
     * @RequestBody 是完整的接受协议体
     */
    @PostMapping("/decreaseNumber")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items) {
        itemService.decreaseNumber(items);
        return JsonResult.ok().msg("减少商品库存成功");
    }

}
